import axios from 'axios'
import cookie from 'js-cookie'
const baseURL = 'http://49.235.166.90:9527'

function request (url = '', params = {}, method = 'get', contentType = 'form', headers = {}, responseType = 'json') {
  contentType === 'form' && (contentType = 'application/x-www-form-urlencoded')
  contentType === 'json' && (contentType = 'application/json')
  contentType === 'file' && (contentType = 'multipart/form-data')
  const query = []
  for (const k in params) {
    query.push(k + '=' + params[k])
  }
  let qs = query.join('&')

  if ((method.toLowerCase() === 'get' || method.toLowerCase() === 'cache') && query.length > 0) {
    url += (url.indexOf('?') < 0 ? '?' : '&') + qs
  }
  if (contentType !== 'application/x-www-form-urlencoded' && method !== 'get') {
    qs = params
  }

  return new Promise((resolve, reject) => {
    axios({
      baseURL,
      timeout: 15000,
      method: method.toLowerCase() === 'cache' ? 'get' : method,
      url: url,
      data: qs,
      headers: {
        Authorization: cookie.get('token'),
        'Content-Type': contentType,
        ...headers
      },
      crossDomain: true,
      withCredentials: true
    }).then(response => {
      if (response.status >= 200 && response.status < 400) {
        const res = response.data
        if (res.code === 0) {
          resolve(res)
        } else if (res.code === 1000) {
          window.location.href = baseURL + '/login'
        } else {
          resolve(res)
        }
      } else {
        const res = {
          code: -1,
          userMsg: `请求出错了：${response.status}`
        }
        resolve(res)
      }
    }, err => {
      console.log(err)
      if ((err + '').indexOf('timeout') > -1) {
        resolve({
          code: -1,
          mag: `请求超时：${url} === 可能是当前网络较慢，或者服务器响应慢，请稍后重试`
        })
      } else {
        resolve({
          code: -1,
          userMsg: `请求失败：${url} === 服务器遇到了一点问题，请稍后重试`
        })
      }
    })
  })
}

export default request
